<template>
	<view>
		<view style="margin: 20px">
			<u--form :model="form" ref="dataForm" labelPosition="left" :rules="rules" labelWidth="180rpx" :labelStyle="{
          color: '#333',
          fontWeight: '500',
          fontSize: '28rpx',
        }">
				<KeywordCheckbox :grid_1="3" :grid_2="2" v-model="form.label"></KeywordCheckbox>
			</u--form>
			<view class="submit-section">
				<u-button type="primary" text="提交" @click="submitForm" shape="circle" size="large" :customStyle="{
            width: '100%',
            height: '90rpx',
            borderRadius: '45rpx',
            fontSize: '32rpx',
            fontWeight: '500',
            background: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
            border: 'none',
            marginTop: '40rpx',
            boxShadow: '0 8rpx 24rpx rgba(74, 144, 226, 0.3)',
          }" />
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		toRefs,
		watch
	} from "vue";
	import {
		showToast,
		showLoading,
		hideLoading
	} from "@/utils/toast";
	import {
		GetSysLabel,
		SysLabelUser
	} from "@/api/userInfo";
	const dataForm = ref(null);
	import {
		onLoad
	} from "@dcloudio/uni-app";

	onLoad(async () => {
		await init();
	});

	// 状态管理
	const state = reactive({
		form: {
			label: [], // 存储选中项的ID
		},
		rules: {
			label: [{
				required: true,
				message: "请至少选择一个关键词",
				trigger: "change"
			}, ],
		},
		checkboxData: {
			long: [], // 长关键词数组
			short: [], // 短关键词数组
		},
	});

	const {
		form,
		rules,
		checkboxData
	} = toRefs(state);
	const isAllChecked = ref(false);

	// 初始化数据
	const init = async () => {
		try {
			showLoading("加载中...");
			const res = await GetSysLabel();

			if (res.code === 10000) {
				// 处理长关键词
				checkboxData.value.long = (res.data.long || []).map((item) => ({
					...item,
					disabled: false,
					checked: item.selected || false,
				}));

				// 处理短关键词
				checkboxData.value.short = (res.data.short || []).map((item) => ({
					...item,
					disabled: false,
					checked: item.selected || false,
				}));

				// 同步选中项
				updateFormLabel();
				// 同步全选状态
				updateAllCheckedStatus();
			} else {
				showToast("数据格式错误");
			}
		} catch (error) {
			showToast("获取数据失败");
			console.error("初始化错误：", error);
		} finally {
			hideLoading();
		}
	};

	// 合并所有选项为一个数组
	const getAllItems = () => {
		return [...checkboxData.value.long, ...checkboxData.value.short];
	};

	// 更新全选状态
	const updateAllCheckedStatus = () => {
		const allItems = getAllItems();
		isAllChecked.value =
			allItems.length > 0 && allItems.every((item) => item.checked);
	};

	// 更新表单选中值
	const updateFormLabel = () => {
		const allItems = getAllItems();
		form.value.label = allItems
			.filter((item) => item.checked)
			.map((item) => item.id);
	};

	// 监听复选框变化，更新全选状态
	watch(
		() => [checkboxData.value.long, checkboxData.value.short],
		() => {
			updateAllCheckedStatus();
			updateFormLabel();
		}, {
			deep: true
		}
	);

	// 单个选项点击事件
	const choose = (item) => {
		item.checked = !item.checked;
	};

	// 全选/取消全选事件
	const allChoose = () => {
		const checked = !isAllChecked.value;
		// 更新长关键词
		checkboxData.value.long.forEach((item) => {
			item.checked = checked;
		});
		// 更新短关键词
		checkboxData.value.short.forEach((item) => {
			item.checked = checked;
		});
		// 更新选中状态
		isAllChecked.value = checked;
		updateFormLabel();
	};

	// 表单提交事件
	const submitForm = async () => {
		if (form.value.label.length === 0) {
			showToast("请至少选择一个关键词");
			return;
		}

		try {
			showLoading("提交中...");
			const res = await SysLabelUser(form.value);

			if (res.code === 10000) {
				showToast("提交成功");
				uni.navigateBack();
			} else {
				showToast(res.msg || "提交失败");
			}
		} catch (error) {
			showToast("提交错误，请重试");
			console.error("提交错误：", error);
		} finally {
			hideLoading();
		}
	};
</script>
<style scoped>
	:deep(.u-grid-item) {
		align-items: baseline !important;
	}

	:deep(.u-checkbox-group) {
		display: block !important;
	}
</style>